# -*- coding: utf-8 -*-
"""
需要复制浏览器的Cookie 到 代码中
只能签到7级吧
"""
import os
import requests
try:
    import cookielib
except:
    from http import cookiejar as cookielib
import json
import logging

#logging.basicConfig(
#    level=logging.DEBUG,
#    format="%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s",
#    datefmt="%Y-%m-%d %H:%M:%S",
#    filename='./signin.log',
#    filemode='w'
#)

COPY_COOKIE_PATH = "cookie.txt"
COOKIE_PATH = "baiducookie.txt"
HEADERS = {
    "Accept": "application/json, text/javascript, */*; q=0.01",
    "Accept-Language": "zh-CN,zh;q=0.8,en;q=0.6",
    "Connection": "keep-alive",
    "Host": "tieba.baidu.com",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36",
}

HEADERS_POST = {
    "Origin": "https://tieba.baidu.com",
    "Referer": "https://tieba.baidu.com/index.html",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36",
}


class OneKey:

    def __init__(self):
        self.session = requests.session()

        # 新的
        if os.path.exists(COOKIE_PATH):
            load_cookiejar = cookielib.LWPCookieJar()
            load_cookiejar.load(COOKIE_PATH, ignore_discard=True, ignore_expires=True)
            load_cookies = requests.utils.dict_from_cookiejar(load_cookiejar)
            self.session.cookies = requests.utils.cookiejar_from_dict(load_cookies)
        else:
            cookie_dict = self.read_cookie()
            requests.utils.add_dict_to_cookiejar(self.session.cookies, cookie_dict)

    @staticmethod
    def handle_cookie(text):
        """
        浏览器复制的字符串形式的cookie，转换成字典
        :type text: str
        :rtype: dict
        """
        l = text.split(";")
        dic = {}
        for i in l:
            index = i.find("=")
            key = i[:index].strip()
            if not key:
                continue
            value = i[index + 1:].strip()
            dic[key] = value
        return dic

    def read_cookie(self):
        """
        读取用户手动输入的cookie
        :rtype: dict
        """
        with open(COPY_COOKIE_PATH) as f:
            cookie = f.read()
        if not cookie:
            raise Exception("{} 不能为空".format(COPY_COOKIE_PATH))
        cookie_dict = self.handle_cookie(cookie)
        return cookie_dict

    def save_cookie(self):
        new_cookie_jar = cookielib.LWPCookieJar()
        # 内部使用set_cookie的方法设置cookie
        requests.utils.cookiejar_from_dict({c.name: c.value for c in self.session.cookies}, new_cookie_jar)
        # 保存到本地文件
        new_cookie_jar.save(COOKIE_PATH, ignore_discard=True, ignore_expires=True)

    def get_tbs(self):
        # 获取tbs
        url = "http://tieba.baidu.com/dc/common/tbs"
        req = self.session.get(url, headers=HEADERS)
        json_data = json.loads(req.text)
        tbs = json_data.get("tbs")
        is_login = json_data.get("is_login")
        if is_login != 1:
            logging.error("tbs return %s", req.text)
            raise Exception("獲取tbs錯誤")
        logging.info("tbs=%s", tbs)
        return tbs

    def one_key_sign(self, tbs=None):
        post_url = "https://tieba.baidu.com/tbmall/onekeySignin1"
        if not tbs:
            tbs = self.get_tbs()
        post_data = {"ie": "utf-8", "tbs": tbs}
        req = self.session.post(post_url, post_data, headers=HEADERS_POST).json()
        if req["error"] == "success":
            return True
        else:
            return False
        logging.info(req.text)

    def run(self):
        """
        启动
        """
        is_success = self.one_key_sign()
        self.save_cookie()
        return is_success

oneKey = OneKey()
oneKey.run()
